package org.zjt.platform.spring.boot.example.common;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class JacksonDateDeserializer extends JsonDeserializer<Date> {

    private static final String dateFormat      = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";

    public JacksonDateDeserializer() {
    }

    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String strDate = p.getText();
        if (StringUtils.isEmpty(strDate)) {
            return null;
        } else {
            strDate = strDate.trim();
            System.out.println("-------------====================="+strDate+"====================--------------------------");
            try {
                SimpleDateFormat e;
                Date dtDate;
                if (strDate.matches("^\\d{4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}\\+\\d{1,4}$")) {
                    e = new SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss.SSSZ", new Locale("CHINESE", "CHINA"));
                    dtDate = e.parse(strDate);
                    return dtDate;
                } else if (strDate.contains("-")) {
                    if (strDate.contains(":")) {
                        e = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    } else {
                        e = new SimpleDateFormat("yyyy-MM-dd");
                    }
                    dtDate = e.parse(strDate);
                    return dtDate;
                } else if (strDate.matches("^\\d+$")) {
                    Long e1 = new Long(strDate);
                    return new Date(e1.longValue());
                } else if (strDate.matches("^[A-Za-z]{3}\\s[A-Za-z]{3}\\s\\d{1,2}\\s(\\d{1,2}:){2}\\d{1,2}\\s[A-Za-z]{3}\\s\\d{4}$")) {
                    e = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
                    dtDate = e.parse(strDate);
                    return dtDate;
                } else {
                    return null;
                }
            } catch (Exception var6) {
                throw new RuntimeException(String.format("parser %s to Date fail", new Object[] { strDate }));
            }
        }
    }

    public Object deserializeWithType(JsonParser p, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws JsonProcessingException, IOException {
        return this.deserialize(p, ctxt);
    }
}
